/**
 * 공통 유틸 에 해당하는 Static class
 * 
 */
var Common = {
	pageSize : 40,
	
	/**
	 * 공통 Div Popup
	 * @param {String} title
	 * @param {Number} width
	 * @param {Number} height
	 * @param {Object} buttons	 * @return {Ext.Window}
	 */
	openDialog : function(title, width, height, buttons, config) {
		var dialog = Ext.widget('window',{			
			id : (config)?config.id:'',
			title : title,
			layout : 'fit',	
			padding : '5 5 5 5',
			width : width,
			height : height,
			autoHight : true,
//			y: (document.body.offsetHeight < height ? 10 :undefined),
//			autoWidth : false,			
			closeAction : 'destory',
//			closable : false,
//			plain : true,
			animate : true,
			modal : true,
			resizable : false,
//			loadScripts : true,
			minButtonWidth : '40', //defaults to 75
			buttons : buttons
		});
		if(config) Ext.apply(dialog, config);
		return dialog;
	},

	/**
	 * 공통 Url Div Popup
	 * @param {String} title
	 * @param {String} url 
	 * @param {Array/Object} url에 post로 넘길 parameter 배열
	 * @param {Number} width
	 * @param {Number} height
	 * @param {Array/Object} button에 대한 배열
	 * @return {Ext.Window}
	 */
	openWindow : function(title, url, params, width, height, buttons) {
		var win = new Ext.Window({
			title : title,			
			layout : 'fit',	
			padding : '10 6 5 6',
			width : width,
			height : height,
			y: (document.body.offsetHeight < height ? 10 :undefined),
			autoWidth : false,
			autoScroll:true,
			closeAction : 'close',			
			closable:true,
			plain : true,
			animate : true,
			modal : true,
			resizable : false,
			loadScripts : true,
			autoLoad : {
				url : url,
				params : !params?false:params
			},
			//minButtonWidth : '40', //defaults to 75
			footerCssClass: 'fbar_blue_button',
			buttons : !buttons?false:buttons
		});
		return win;
	},
	
    /**  
	 *  팝업창을 띄우고 화면의 중앙으로 이동한다.
	 *  @param  {String} 팝업창의 URL
	 *  @param  {String} 팝업창 이름
	 *  @param  {Number} 팝업창의 width
	 *  @param  {Number} 팝업창의 height
	 *  @param  {String} 추가기능 (ex. 'scrollbars=no, resizable=yes' )
	 *  @return  {window} 객체
	 *  예제) openWindowCenter(url, 'popupCalendar', 180, 195, 'scrollbars=no');
	 */
	openPopUp : function(theURL, winName, width, height, features) {
		//  화면 중앙의 좌표값 계산
		var leftX = screen.width / 2 - width / 2;
		var topY = -75 + screen.height / 2 - height / 2;
		//  팝업창 크기 설정
		var featuresValue = 'width=' + width + ',height=' + height;
		featuresValue += ',left=' + leftX + ',top=' + topY;
		//  추가 속성 지정		if (features.length > 0) featuresValue += ',' + features; 
		//  창을 open 한다.
		var win = window.open(theURL, winName, featuresValue);
		win.focus();
		return win;
	},
	
	/**
	 * Enter Key 발생시 Callback 함수 호출
	 * @param {Object} callBack 함수 
	 */
	enterCallFn : function(callBackFn){
		if(window.event.keyCode == 13){
			callBackFn();
			return;
		}
		return;
	},
	
	/**
	 * 공통 Form panel
	 * @private
	 * @param {Object} items 
	 * @return {Ext.form.FormPanel}
	 */
	formPanel : function(items){
		return new Ext.FormPanel({
	        autoWidth : true,
	        autoHeight : true,
	        defaultType: 'textfield',
	        frame : false,
	        border:true,
			bodyStyle:{borderRight:'0px',borderBottom:'0px'},
			minButtonWidth : '40', //defaults to 75
	        items:items?items:null
	    });
	},
	
	/**
	 * ExtJS Grid에서 editor인 ComboBox가 Redering될때 현재 선택값이 나오도록 변환
	 * @param {Ext.form.ComboBox} combo
	 * @return {String} 선택된 combo의 description
	 */
	rendererCombo:function(combo){
        return function(value, meta, record){
		    var returnValue = value;
		    var valueField = combo.valueField;
		    var idx = combo.store.findBy(function(record) {
		        if(record.get(valueField) == value) {
		            returnValue = record.get(combo.displayField);
		            return true;
		        }
		    });
		    if(idx < 0 && value == 0) {
		        returnValue = '';
		    }
		    
		    return returnValue;
	    };
	},
	
	/**
	 * Grid Date type의 변환
	 * @param {TimeStamp object/Date} value
	 * @return {String/Date}
	 */
	rendererFormatDate : function (value){
		if(value instanceof Date)
			return value ? value.dateFormat('Y-m-d') : '';
		else
			return value;
    },
	
	/**
	 * Data Array를 Parameter로 받은 Combo
	 * @param {Array} data
	 * @return {Ext.form.Combobox}
	 */
	getArrayCombo : function(data){
		var config = {
			data : data
		};
		return Common.getArrayComboField(config);
	},
	
	/**
	 * form field에 사용되는 array combo
	 * config properties
	 * - id
	 * - title
	 * - fieldLabel
	 * - data
	 * @param {JSON} data
	 * @return {Ext.form.Combobox}
	 */
	getArrayComboField : function(config){
		var store = new Ext.data.SimpleStore({
			fields : ['key', 'value'],
			data : config.data
		});
		var combo = new Ext.form.ComboBox({
			id : config.id,
			store: store,
    		valueField: 'key',
          	displayField:'value',
            typeAhead: true,
            mode: 'local',
            forceSelection: true,
            triggerAction: 'all',
            selectOnFocus:true,
			lazyRender:true,
    		editable: false,
    		listeners : config.listeners,
    		value : (config.data[0] instanceof String)? config.data[0]:config.data[0][0] 
		});
		Ext.applyIf(combo,config);
		return combo;
	},
	
	/**
	 * Code Combo
	 * @param {String} id
	 * @param {String} groupId
	 * @return {Ext.form.ComboBox}
	 */
	getCodeCombo : function(config) {
		if (typeof config.valueField == "undefined") config.valueField = "systemCode";
		if (typeof config.displayField == "undefined") config.displayField = "text";
		
		var store = new Ext.data.JsonStore({
			autoLoad:true,						
			fields: [
				{name : config.valueField},
				{name : config.displayField}
			],
			url : '',
			baseParams:{
				systemCode : config.systemCode
			}
		});
		
		var combo = new Ext.form.ComboBox({
			id : config.id,
			name : config.name,
			hiddenName : config.name,
			store: store,
    		valueField: config.valueField,
          	displayField: config.displayField,
            typeAhead: true,
            mode: 'local',
            forceSelection: true,
            triggerAction: 'all',
            selectOnFocus:true,
			lazyRender:true,
    		editable: false,
    		allowBlank: config.allowBlank,
    		listeners : config.listeners
		});
      	Ext.apply(combo, config);
      	return combo;
	},
	
	/**
	 * ajax 500 경고 메세지
	 * @param {Object} result
	 * @param {Object} request
	 */
	failureMessage : function (result, request) {
		Common.hideWaitBox();
		if(typeof(result.responseText) == 'undefined') return;
    	Ext.MessageBox.show({
           title : LocaleUtil.getMessage('warrning'),
           msg : '<ul style=font-size:10pt;padding:0px>'+result.responseText+'</ul>',
           buttons : Ext.MessageBox.OK,   
           //cls : 'blue_button',
           icon : Ext.MessageBox.WARNING
    	});
	},
	
	/**
	 * Ext-js Submit 500 경고 메세지
	 * @param {Object} form
	 * @param {Object} action
	 */
	failureMessageSubmit : function (form, action) {
		Ext.MessageBox.show({
           title : LocaleUtil.getMessage('warrning'),
           msg : '<ul style=font-size:10pt;padding:0px>'+action.result.msg+'</ul>',
//           msg : action.response.responseText,
           buttons : Ext.MessageBox.OK,   
           //cls : 'blue_button',
           icon : Ext.MessageBox.WARNING
       });
	},
	
	alert : function(title,message){
		Ext.MessageBox.show({
           title : title,
           msg : '<ul style=font-size:10pt;padding:0px>'+message+'</ul>',
           buttons : Ext.MessageBox.OK,   
           icon : Ext.MessageBox.WARNING
       });
	},
	
	/**
	 * 확인 창(close 버튼이 없는 확인 창)
	 * @param {String} title
	 * @param {String} msg
	 * @param {Function} fn
	 * @param {Object} scope
	 * @return {Ext.MessageBox}
	 */
	confirm: function(title, msg, fn, scope){
		return Ext.MessageBox.show({
            title : title,
            msg : msg,
            fn: fn,
            minWidth  : 300,
            //cls : 'blue_button',
            bodyCfg :{
	            padding : ' 30 10 10 10',
	            margins : ' 30 30 30 30'
	            	
			},
            scope : scope,
            icon: Ext.MessageBox.QUESTION,
            buttons: Ext.MessageBox.YESNO,
            closable: false
        });
	},
	
	/**
	 * 선택된 record 삭제 확인 창(close 버튼이 없는 확인 창)
	 * @param {Ext.grid.GridPanel} grid
	 * @param {Function} callBackFn
	 * @param {Object} scope
	 */
	confirmDeleteRecords: function(grid, callBackFn, scope){
		if(!grid.getSelectionModel().getSelections() || grid.getSelectionModel().getSelections().length == 0)
			return;
			
		Common.confirm(LocaleUtil.getMessage('confirm'),'선택한 항목을 삭제하시겠습니까?',function(btn){
			if(btn == 'yes')
        		callBackFn.createDelegate(scope)();
		},scope);
	},
	
	/**
	 * System Log를 생성한다.
	 * opCode는 SEC_PAM_LOG_OP 테이블 참조
	 * @param {Object} opData
	 */
	insertLog : function(opData){
//		Ext.Ajax.request({
//			url:'log.do?method=insertLog',
//			params:{
//				opCode : opData.opCode,
//				objectId : opData.objectId,
//				objectData : opData.objectData
//			},			
//			failure: Common.failureMessage
//		});
	},
	
	/**
	 * 컬럼 필드 method
	 * @param {Array} columns
	 * @return {Ext.Panel}
	 * @private
	 */
	getColumnFiled : function(columns){
		return {
            layout : 'column',
            border : false,
            defaults : {
                columnWidth : .5,
                layout : 'form',
                border : false,
                defaultType: 'textfield'
            },
            items : [{
                items : columns[0]
            }, {
                items : columns[1]
            }]
        };
	},
	
	/**
	 * viewConfig
	 * @param {Boolean} forceFit
	 * @return {Object}
	 */
	viewConfig: function(forceFit) {
		return {
			forceFit : (forceFit?true:false),
			deferEmptyText:false,
			emptyText : LocaleUtil.getMessage('rms.msg.noData')
		};		
	},
	
	/**
	 * 공통 PagingToolbar
	 * @param {Ext.data.Store} store
	 * @param {Number} pageSize
	 * @return {Ext.PagingToolbar}
	 */
	pagingToolBar : function(store, pageSize){
		Ext.apply(store, {
			pageSize: (!pageSize ? Common.pageSize :pageSize)
		});
		return new Ext.create('Ext.toolbar.Paging',{
	        margins: '5 0 0 0',
	        store: store,
	        buttonAlign: 'center',
	        displayInfo: true
	    });	
	},
	
	/**
	 * 중복된 배열을  merge 한다.
	 * @param {Array} duplicateArray
	 * @return {Array} uniqueArray
	 */
	mergeDuplicateArray : function(duplicateArray){
    	var uniqueArray = [];
    	
    	for (var i = 0; i < duplicateArray.length; i++) {
    		var isDuplicated = false;
    		for (var j = 0; j < uniqueArray.length; j++) {
    			if(uniqueArray[j] == duplicateArray[i])
    				isDuplicated = true;
    		}
    		
    		if(!isDuplicated)
    			uniqueArray[uniqueArray.length] = duplicateArray[i];
    	}
    	
    	return uniqueArray;
    },
    
    /**
     * Download 전용 iframe에 url 호출
     * @param {String} url
     */
    downloadIframe : function(url){
    	var iframe = Ext.getDom('downloadIframe');		
		if(iframe) iframe.src = url;
		else		
			Ext.DomHelper.append(document.body, {
			    tag: 'iframe',
			    id : 'downloadIframe',
			    frameBorder: 0,
			    width: 0,
			    height: 0,
			    css: 'display:none;visibility:hidden;height:1px;',
			    src: url
			});
    },
    
    /**
     * wait 메세지 출력
     * @param {Ext.MessageBox} message
     */
    showWaitBox : function(message){    	
    	if(message)
    		Ext.MessageBox.wait(message);
    	else
    		Ext.MessageBox.wait(LocaleUtil.getMessage('rms.msg.waitToSaving'));
    },
    
    /**
     * watting message box를 사라지게 한다.
     */
    hideWaitBox : function(){
    	Ext.MessageBox.hide();
    },
    
    /**
     * 다국어지원을 위한 
     * @param {String} key
     * @return {String}
     */
    getMessage : function(key){
    	if(!arguments) return '';    	
    	var argStr = "String.format('" + eval('locale.'+key) + "'";
    	if(arguments.length > 1){
	    	for (var i = 1; i < arguments.length; i++) {
	    		argStr += ",'"+arguments[i] + "'";
	    	}
	    	argStr += ')';
    		return eval(argStr);
    	}
    	return eval('locale.'+key);
    },    
	
    nullToEmpty : function (str) {
        if (str == null) str = "";
        return str;
    },
	
	/**
	 * 공통 chart style
	 * @type 
	 */
	chartStyle: function(){
		return {
	        padding: 10,
	        animationEnabled: true,
	        font: {
	            name: 'Tahoma',
	            color: 0x444444,
	            size: 11
	        },
	        dataTip: {
	            padding: 5,
	            border: {
	                color: 0x99bbe8,
	                size:1
	            },
	            background: {
	                color: 0xDAE7F6,
	                alpha: .9
	            },
	            font: {
	                name: 'Tahoma',
	                color: 0x15428B,
	                size: 10,
	                bold: true
	            }
	        },
	        xAxis: {
	            color: 0x69aBc8,
	            majorTicks: {color: 0x69aBc8, length: 4},
	            minorTicks: {color: 0x69aBc8, length: 2},
	            majorGridLines: {size: 1, color: 0xeeeeee}
	        },
	        yAxis: {
	            color: 0x69aBc8,
	            majorTicks: {color: 0x69aBc8, length: 4},
	            minorTicks: {color: 0x69aBc8, length: 2},
	            majorGridLines: {size: 1, color: 0xdfe8f6}
	        }
	    };
	},
	
	getHwTypeCombo : function(config){
		var store = new Ext.data.JsonStore({
			autoLoad:false,						
			fields: ['type','name'],
			proxy : {
				type : 'ajax',
				url : 'hardware/getHardwareTypes.do'
			},
			listeners : {
				load: function(store){
					var rec = { 'type' : '', 'name' : 'All' };
					store.insert(0,rec);
				}
			}
		});
		
		var combo = new Ext.form.ComboBox({
			id : config.id,
			name : config.name,
			store: store,
            typeAhead: true,
//            mode: 'local',
            valueField: 'type',
          	displayField:'name',
            forceSelection: true,
//            triggerAction: 'all',
            selectOnFocus:true,
			lazyRender:true,
    		editable: false/*,
    		allowBlank: config.allowBlank,
    		listeners : config.listeners*/
		});
      	Ext.apply(combo, config);
      	
      	return combo;
	},
	
	getMakeRe : function(){
		return /^([a-zA-Z0-9]*)$/;
	},
	
	getStateName : function(state){
		if(state == 'OKE'){
			return LocaleUtil.getMessage('rms.label.normal');//정상
		}else{
			return LocaleUtil.getMessage('rms.fault.'+state);
		}
	},
	
	getHowToRestoreAboutState : function(state){
		return LocaleUtil.getMessage('rms.fault.'+state+'restore');
	},
	
	formSubmit : function(formObj, scope){
		Common.showWaitBox(LocaleUtil.getMessage('rms.msg.waitToSaving'));
		Ext.Ajax.request({
			url : formObj.url,
			params : formObj.params,
			scope : (scope)?scope:this,
			success : function(result, request){
				Common.hideWaitBox();
				if(formObj.callBackFn){
					formObj.callBackFn();
				}
				if(formObj.closeDialog){
					formObj.closeDialog.close();
				}
				if(formObj.reloadPanelId){
					Ext.getCmp(formObj.reloadPanelId).getStore().reload();
				}
			},
			failure: Common.failureMessage
		});
	}
};